package com.viewpagertext.fragments;

import static androidx.databinding.DataBindingUtil.setContentView;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.RecyclerView;
import androidx.viewpager.widget.ViewPager;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.viewpagertext.DBHelper.AppDatabase;
import com.viewpagertext.DBHelper.Dao.SearchHistoryDao;
import com.viewpagertext.DBHelper.Dao.StarredSongDao;
import com.viewpagertext.Model.SearchHistory;
import com.viewpagertext.R;
import com.viewpagertext.activitys.PlayActivity;
import com.viewpagertext.constructor.MessageEvent;
import com.viewpagertext.constructor.SongsDatas;
import com.viewpagertext.utils.HttpUtil;

import org.greenrobot.eventbus.EventBus;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import okhttp3.Call;
import okhttp3.Response;

import static com.viewpagertext.adapters.MusicGridAdapter.FindImgUrlPath;
import static com.viewpagertext.adapters.MusicGridAdapter.SearchName;

public class SearchFragment extends Fragment {
    SearchHistoryDao helper = AppDatabase.getInstance().searchHistoryDao();
    private ImageView iv_searchBack;
    private ViewPager viewPager;
    private Button btn_search;
    private EditText et_searchText;
    //    private ListViewForScrollView listViewForScrollView;
    private TextView tv_historyText, tv_clearHistory;

    private String FreeSongPath1 = "https://www.hhlqilongzhu.cn/api/dg_qqmusic.php?gm=";
    private String FreeSongPath2 = "&n=1&type=json";
    private List<SongsDatas> searchList = new ArrayList<>();
    private int count = 0;
    private View view;

    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        view = inflater.inflate(R.layout.fragment_search, container, false);
        viewPager = getActivity().findViewById(R.id.play_viewpager);
        initView();
        setListeners();
        return view;
    }

    /**
     * 获取相对应的控件
     */
    private void initView() {
        iv_searchBack = view.findViewById(R.id.iv_searchback);
        btn_search = view.findViewById(R.id.btn_search);
        et_searchText = view.findViewById(R.id.et_searchtext);
//        listViewForScrollView=view.findViewById(R.id.search_listview);
        tv_historyText = view.findViewById(R.id.tv_searchhistory);
        tv_clearHistory = view.findViewById(R.id.tv_clearsearch);
        System.out.println("初始化SrF");
    }

    /**
     * 实现搜索功能
     */
    private void setListeners() {

        /**
         * 存放搜索历史的表
         */


        /**
         * 返回服务页面
         */
        iv_searchBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                getActivity().finish();

            }
        });

        /**
         * 给搜索历史传入空
         */
        tv_historyText.setText(" ");
        List<SearchHistory> sr = helper.getAll();


        if (sr.size() == 0) {
            tv_historyText.append("没有搜索历史");
            Toast.makeText(getActivity(), "没有搜索历史", Toast.LENGTH_SHORT).show();
        } else {
            for (SearchHistory item : sr) {
                tv_historyText.append(item.getName() + " ");
            }


        }


        tv_clearHistory.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                System.out.println("删除所有");
                helper.deleteAll();
                getActivity().recreate();
            }
        });


        /**
         * 搜索按钮的监听
         */
        btn_search.setOnClickListener(new View.OnClickListener() {
            @SuppressLint("SuspiciousIndentation")
            @Override
            public void onClick(View v) {

                String obtain = et_searchText.getText().toString().trim();
                /**
                 * 下一次点击搜索按钮时清空前一次搜索列表
                 */
                count++;
                if (count % 1 == 0) {
                    searchList.clear();
                }
                /**
                 * 将搜索框内容放入到搜索历史当中去
                 */
                tv_historyText.append(obtain + " ");
                /**
                 * 将搜索框内容放入到搜索历史表当中去
                 */

                if (helper.findByName(obtain) == null) {
                    System.out.println("只有一次");
                    helper.insertByName(obtain);
                }


                /**
                 * 判断搜索框是否为空
                 */
                if (obtain.isEmpty()) {
                    Toast.makeText(getActivity(), "搜索框为空", Toast.LENGTH_SHORT).show();
                    searchList.clear();
                } else {
                    /**
                     * 现在要做的就是找到歌曲，然后跳转到ListFragment里面,关键词为Obtain
                     */
                    tv_historyText.setText(" ");
                    List<SearchHistory> sr = helper.getAll();


                    if (sr.size() == 0) {
                        tv_historyText.append("没有搜索历史");
                        Toast.makeText(getActivity(), "没有搜索历史", Toast.LENGTH_SHORT).show();
                    } else {
                        for (SearchHistory item : sr) {
                            tv_historyText.append(item.getName() + " ");
                        }

                    }

                    HttpUtil.sendOkHttpRequest(FreeSongPath1 + obtain + FreeSongPath2, new okhttp3.Callback() {
                        @Override
                        public void onFailure(Call call, IOException e) {
                            Intent intent = new Intent(getActivity(), PlayActivity.class);
                            String ft = "查找结果：";
                            SearchName = obtain;
                            EventBus.getDefault().postSticky(new MessageEvent(ft));//发送
                            getActivity().startActivity(intent);
                            // Toast.makeText(getActivity(),"IO发生异常",Toast.LENGTH_SHORT).show();
                        }

                        @Override
                        public void onResponse(Call call, Response response) throws IOException {
                            String ListResponseData = response.body().string();//得到服务器返回的具体内容
                            JSONObject jsonObject = null;
                            try {

                                jsonObject = new JSONObject(ListResponseData);
                                int code = jsonObject.getInt("code");
                                if (code == 200) {
                                    JSONObject dataObject = jsonObject.getJSONObject("data");
                                    String pic = dataObject.getString("cover");
                                    String singer = dataObject.getString("song_singer");
                                    FindImgUrlPath = pic;//获取图片地址设置全局供ListFragment接收
                                    SearchName = obtain;//获取FindFragment歌单ID
                                    String ft = "查找结果：" + "(最火歌手:" + singer + ")";
                                    Intent intent = new Intent(getActivity(), PlayActivity.class);
                                    EventBus.getDefault().postSticky(new MessageEvent(ft));//发送
                                    getActivity().startActivity(intent);

                                } else {
                                    Intent intent = new Intent(getActivity(), PlayActivity.class);
                                    String ft = "查找结果：";
                                    SearchName = obtain;
                                    EventBus.getDefault().postSticky(new MessageEvent(ft));//发送
                                    getActivity().startActivity(intent);
                                }


                            } catch (JSONException e) {
                                Intent intent = new Intent(getActivity(), PlayActivity.class);
                                String ft = "查找结果：";
                                SearchName = obtain;
                                EventBus.getDefault().postSticky(new MessageEvent(ft));//发送
                                getActivity().startActivity(intent);
                            }

                        }
                    });


                }


            }
        });
        /**
         * 搜索列表的点击事件
         */

    }

    /**
     * 适配器获取数据库中搜索表所存放的内容
     */


    SongsDatas ssHot;

    public SearchFragment() {
        // Required empty public constructor
    }


}